package com.yanqu.road.server.gameplayer.module.activity.newyear2023;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.newyear2023.FireWorkUserData;
import com.yanqu.road.entity.activity.newyear2023.config.FireWorkConfig;
import com.yanqu.road.entity.bag.UseGoodsResult;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.OpenGoodsBagResult;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogFireWorkNormalFire;
import com.yanqu.road.entity.log.LogFireWorkSpecialFire;
import com.yanqu.road.entity.player.UserActivityScore;
import com.yanqu.road.logic.bussiness.activity.FireWorkBusiness;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.FireWorkProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityMallModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.logic.bag.BaseUseGoods;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.newyear2023.FireWorkMgr;
import com.yanqu.road.server.manger.config.GoodsBagMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;


public class FireWorkModule extends GeneralModule {


    private FireWorkUserData userData;

    public FireWorkModule(GamePlayer player) {
        super(player);
    }

    public FireWorkUserData getUserData(){
        return userData;
    }


    public void sendSelf(String content){
        if(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()) != 666){
            return;
        }
        ActivityInfo activity1Info = FireWorkMgr.getTypeActivity(1);
        if(activity1Info != null){
            if(content.equals("24923")){
                FireWorkProto.FireWorkFireReqMsg.Builder reqMsg = FireWorkProto.FireWorkFireReqMsg.newBuilder();
                reqMsg.setActivityId(activity1Info.getActivityId());
                reqMsg.setItemId(123104);
                reqMsg.setCount(10);
                player.sendPacket(Protocol.S_FIREWORK_FIRE, reqMsg);
            }
        }
        ActivityInfo activityInfo = FireWorkMgr.getTypeActivity(2);
        if(activityInfo != null){
            if(content.equals("24926")){
                FireWorkProto.FireWorkEnterRedPacketHomeReqMsg.Builder reqMsg = FireWorkProto.FireWorkEnterRedPacketHomeReqMsg.newBuilder();
                reqMsg.setActivityId(activityInfo.getActivityId());
                reqMsg.setNo(-1);
                player.sendPacket(Protocol.S_FIREWORK_RP_ENTER, reqMsg);
            }
            if(content.equals("24927")){
                FireWorkProto.FireWorkOpenRedPacketTableReqMsg.Builder reqMsg = FireWorkProto.FireWorkOpenRedPacketTableReqMsg.newBuilder();
                reqMsg.setActivityId(activityInfo.getActivityId());
                reqMsg.setMessage("sprise amotnoat fa k");
                player.sendPacket(Protocol.S_FIREWORK_RP_OPEN, reqMsg);
            }
            if(content.equals("24928")){
                FireWorkProto.FireWorkOpenRedPacketReqMsg.Builder reqMsg = FireWorkProto.FireWorkOpenRedPacketReqMsg.newBuilder();
                reqMsg.setActivityId(activityInfo.getActivityId());
                reqMsg.setNo(0);
                player.sendPacket(Protocol.S_FIREWORK_RP_JOIN, reqMsg);
            }
            if(content.equals("24931")){
                FireWorkProto.FireWorkRobAddMessageReqMsg.Builder reqMsg = FireWorkProto.FireWorkRobAddMessageReqMsg.newBuilder();
                reqMsg.setActivityId(activityInfo.getActivityId());
                reqMsg.setNo(0);
                reqMsg.setMessage("adasd");
                player.sendPacket(Protocol.S_FIREWORK_RP_ROB_MESSAGE, reqMsg);
            }
            if(content.equals("24932")){
                FireWorkProto.FireWorkRandomRobRedPacketReqMsg.Builder reqMsg = FireWorkProto.FireWorkRandomRobRedPacketReqMsg.newBuilder();
                reqMsg.setActivityId(activityInfo.getActivityId());
                player.sendPacket(Protocol.S_FIREWORK_RP_ROB_RANDOM, reqMsg);
            }
            if(content.equals("24932")){
                FireWorkProto.FireWorkRedPacketTableRobUserReqMsg.Builder reqMsg = FireWorkProto.FireWorkRedPacketTableRobUserReqMsg.newBuilder();
                reqMsg.setActivityId(activityInfo.getActivityId());
                reqMsg.setNo(0);
                player.sendPacket(Protocol.S_FIREWORK_RP_ROB_USER, reqMsg);
            }
        }
    }

    public int fireWorkFire(int activityId, int itemId, int count) {
        FireWorkConfig config = FireWorkMgr.getActivityConfigInfo(activityId);
        FireWorkProto.FireWorkFireRespMsg.Builder respMsg = FireWorkProto.FireWorkFireRespMsg.newBuilder();
        respMsg.setRet(0);
        UseGoodsResult result = null;
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(itemId);
        BaseUseGoods useGoodsEntity = BaseUseGoods.getUseGoodsEntity(player, goodsInfo, activityId, "");
        if(null == useGoodsEntity){
            return GameErrorCode.E_BAG_ITEM_USE_TYPE_UNKNOWN;
        }
        long noticeCount = 0;
        for(int i = 0; i < count ; i++){
            result = useGoodsEntity.useGoods(1);
            if(result.getRet() == 0){
                if(itemId == FireWorkMgr.getNmFireId()){
                    if(config.isSpecialChance()){
                        Property spReward = PropertyHelper.parseStringToProperty(config.getSpFireId() + "=1");
                        player.getModule(CurrencyModule.class).addCurrency(spReward, eLogMoneyType.FireWork2023,eLogMoneyType.FireWork2023ActivityFireReward);
                        Property allReward = PropertyHelper.parseStringToProperty(result.getReward());
                        allReward.addProperty(spReward);
                        result.setReward(PropertyHelper.parsePropertyToString(allReward));
                    }
                }
                respMsg.addReward(result.getReward());
                log(goodsInfo,result,count);
                noticeCount++;
            }else{
                if(noticeCount > 0 && itemId == FireWorkMgr.getSpFireId()){
                    player.notifyListener(eGamePlayerEventType.FireWorkSpUseCount.getValue(), noticeCount);
                }
                return result.getRet();
            }
        }
        //2023烟花祈愿 燃放定制爆竹
        if(noticeCount > 0 && itemId == FireWorkMgr.getSpFireId()){
            player.notifyListener(eGamePlayerEventType.FireWorkSpUseCount.getValue(), noticeCount);
        }
        player.sendPacket(Protocol.U_FIREWORK_FIRE, respMsg);
        return 0;
    }

    private void log(GoodsInfo goodsInfo,UseGoodsResult result, long count){
        try {
            if(goodsInfo.getGoodsId() == FireWorkMgr.getNmFireId()){
                FireWorkUserData userData = getUserData();
                if(userData != null){
//                    LogMgr.addLogFireWorkNormalFire(new LogFireWorkNormalFire(
//                            player.getUserId(),userData.getActivityId(),count == 10 ?2:1, result.getReward(),userData.getIntegral()
//                    ));
                    AutoLogMgr.add(new LogFireWorkNormalFire(
                            player.getUserId(), userData.getActivityId(), count == 10 ? 2 : 1, result.getReward(), userData.getIntegral()
                    ));
                }
            }else if(goodsInfo.getGoodsId() == FireWorkMgr.getSpFireId()){
                FireWorkUserData userData = getUserData();
                if(userData != null){
//                    LogMgr.addLogFireWorkSpecialFire(new LogFireWorkSpecialFire(
//                            player.getUserId(),userData.getActivityId(),result.getReward()
//                    ));
                    AutoLogMgr.add(new LogFireWorkSpecialFire(
                            player.getUserId(),userData.getActivityId(),result.getReward()
                    ));
                }
            }
        } catch (Exception e) {
            GoodsBagMgr.getLogger().error("error : ", e);
        }
    }

    public void addScore(BigInteger num,eLogMoneyType son){
        ActivityInfo activityInfo = FireWorkMgr.getTypeActivity(1);
        if(activityInfo != null){
            initUserData(activityInfo.getActivityId());
        }
        //邮件领取的补发不加入下一次活动
        if(userData != null && son != eLogMoneyType.MailOpen){
            userData.setIntegral(userData.getIntegral() + num.longValue());
            player.notifyListenerAndSync(eGamePlayerEventType.FireWorkScoreRank.getValue(),BigInteger.valueOf(userData.getIntegral()));
            syncUserData();
            updateUserHappyValue();
        }
    }

    //更新喜庆值，登录也要更新
    private void updateUserHappyValue(){
        FireWorkProto.CrossUpdateUserConditionReqMsg.Builder upMsg = FireWorkProto.CrossUpdateUserConditionReqMsg.newBuilder();
        upMsg.setActivityId(userData.getActivityId());
        FireWorkProto.CrossUpdateUserConditionMsg.Builder cMsg = FireWorkProto.CrossUpdateUserConditionMsg.newBuilder();
        cMsg.setActivityId(userData.getActivityId());
        cMsg.setConditionType(eGamePlayerEventType.FireWorkHappyValue.getValue());
        cMsg.setUserId(userData.getUserId());
        cMsg.setValue(userData.getIntegral() + "");
        cMsg.setParam("");
        upMsg.addData(cMsg);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_CONDITION_ACTIVITY_UPDATE, upMsg);
        GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
    }

    public int redPacketEnter(int activityId,int no){
        FireWorkProto.CrossFireWorkEnterRedPacketReqMsg.Builder msg = FireWorkProto.CrossFireWorkEnterRedPacketReqMsg.newBuilder();
        msg.setActivityId(activityId);
        msg.setNo(no);
        msg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId())));
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_FIREWORK_ACTIVITY_ENTER, msg);
        GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
        return 0;
    }

    public int openRedPacketTable(int activityId,String message){
        FireWorkProto.CrossFireWorkOpenRedPacketTableReqMsg.Builder msg = FireWorkProto.CrossFireWorkOpenRedPacketTableReqMsg.newBuilder();
        msg.setActivityId(activityId);
        msg.setIntegral(userData.getIntegral());
        msg.setMessage(message);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_FIREWORK_ACTIVITY_OPEN, msg);
        GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
        return 0;
    }

    public int robRedPacketTable(int activityId,int no){
        FireWorkProto.CrossFireWorkRobRedPacketTableReqMsg.Builder msg = FireWorkProto.CrossFireWorkRobRedPacketTableReqMsg.newBuilder();
        msg.setActivityId(activityId);
        msg.setNo(no);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_FIREWORK_ACTIVITY_ROB, msg);
        GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
        return 0;
    }

    public int tableRobUserList(int activityId,int no){
        FireWorkProto.CrossFireWorkTableRobUserListReqMsg.Builder msg = FireWorkProto.CrossFireWorkTableRobUserListReqMsg.newBuilder();
        msg.setActivityId(activityId);
        msg.setNo(no);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_FIREWORK_ACTIVITY_ROB_USER_LIST, msg);
        GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
        return 0;
    }

    public int robRedPacketRandom(int activityId){
        FireWorkProto.CrossFireWorkRobRedPacketRandomReqMsg.Builder msg = FireWorkProto.CrossFireWorkRobRedPacketRandomReqMsg.newBuilder();
        msg.setActivityId(activityId);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_FIREWORK_ACTIVITY_ROB_RANDOM, msg);
        GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
        return 0;
    }


    public int checkCommon(int activityId,int type){
        ActivityInfo activityInfo = FireWorkMgr.getTypeActivity(type);
        if(!FireWorkMgr.isActivityInShowTime(activityId) || activityInfo == null || activityInfo.getActivityId() != activityId){
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if(type == 2){
            FireWorkConfig config = FireWorkMgr.getActivityConfigInfo(activityId);
            if(!config.isRedPacketOpen()){
                return GameErrorCode.E_FIREWORK_RED_TABLE_NOT_OPEN;
            }
        }
        if(!SystemOpenMgr.systemOpen(player, eSystemId.FireWork2023.getValue())){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        return 0;
    }

    @Override
    public boolean loadData() {
        if(SystemOpenMgr.systemOpen(player, eSystemId.FireWork2023.getValue())){
            ActivityInfo activityInfo = FireWorkMgr.getTypeActivity(1);
            if(activityInfo != null && FireWorkMgr.isActivityInShowTime(activityInfo.getActivityId())){
                userData = FireWorkBusiness.getUserData(getUserId(),activityInfo.getActivityId());
                if(userData == null){
                    initUserData(activityInfo.getActivityId());
                }
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        if(userData != null){
            if(userData.isInsertOption()){
                FireWorkBusiness.addUserData(userData);
            }else if(userData.isUpdateOption()){
                FireWorkBusiness.updateUserData(userData);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        if(SystemOpenMgr.systemOpen(player, eSystemId.FireWork2023.getValue())){
            ActivityInfo activityInfo = FireWorkMgr.getTypeActivity(1);
            if(activityInfo != null && FireWorkMgr.isActivityInShowTime(activityInfo.getActivityId())){
                try {
                    initUserData(activityInfo.getActivityId());
                    UserActivityScore userActivityScore = player.getModule(ActivityMallModule.class).getUserActivityScore(activityInfo.getActivityId(), FireWorkMgr.getScoreId());
                    if (userActivityScore != null) {
                        long totalScore = userActivityScore.getTotalScore();
                        if (totalScore > userData.getIntegral()) {
                            log.info("玩家{}数据不一样，原先是{},改成{}",player.getUserId(),userData.getIntegral(),totalScore);
                            userData.setIntegral(totalScore);
                            player.notifyListenerAndSync(eGamePlayerEventType.FireWorkScoreRank.getValue(), BigInteger.valueOf(userData.getIntegral()));
                        }
                    }
                } catch (Exception e) {
                    log.error("FireWorkModule afterLogin error", e);
                }
                syncUserData();
                updateUserHappyValue();
            }
        }
    }

    public void syncUserData(){
        ActivityInfo activityInfo = FireWorkMgr.getTypeActivity(1);
        if(activityInfo != null && FireWorkMgr.isActivityInShowTime(activityInfo.getActivityId())){
            FireWorkProto.FireWorkUserDataSyncMsg.Builder syncMsg = FireWorkProto.FireWorkUserDataSyncMsg.newBuilder();
            syncMsg.setActivityId(activityInfo.getActivityId());
            syncMsg.setIntegral(userData.getIntegral());
            player.sendPacket(Protocol.U_FIREWORK_DATA_SYNC, syncMsg);


            if(FireWorkMgr.getRedPacketActivityId() != 0){
                //跨服的自己的数据同步
                FireWorkProto.CrossFireWorkSyncUserDataReqMsg.Builder msg = FireWorkProto.CrossFireWorkSyncUserDataReqMsg.newBuilder();
                msg.setActivityId(FireWorkMgr.getRedPacketActivityId());
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C2_FIREWORK_ACTIVITY_CROSS_DATA_SYNC, msg);
                GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
            }
        }
    }


    public void initUserData(int activityId){
        if(userData == null || userData.getActivityId() != activityId){
            FireWorkUserData tempUserData = new FireWorkUserData();
            tempUserData.setActivityId(activityId);
            tempUserData.setUserId(getUserId());
            tempUserData.setIntegral(0);
            tempUserData.setInsertOption();
            userData = tempUserData;
        }
    }

    /**
     * 系统解锁
     */
    public void initSystem() {
        ActivityInfo activityInfo = FireWorkMgr.getTypeActivity(1);
        if(activityInfo != null && FireWorkMgr.isActivityInShowTime(activityInfo.getActivityId())){
            initUserData(activityInfo.getActivityId());
            syncUserData();
        }
    }


}
